package com.robot.orders.service;

import com.alibaba.fastjson.JSON;
import com.robot.orders.client.MemberClient;
import com.robot.orders.dao.OrdersDao;
import com.robot.orders.pojo.Orders;
import com.robot.orders.pojo.Purchase;
import com.robot.orders.pojo.client.Coupon;
import com.robot.orders.pojo.client.Member;
import com.robot.orders.pojo.client.Store;
import com.robot.orders.pojo.vo.OrdersRequestModel;
import entity.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * orders服务层
 *
 * @author wuyunbin
 */
@Service
public class OrdersService {
    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private IdWorker idWorker;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * member表status=0-禁用 1-启用
     */
    private String memberStatusEnable = "1";

    /**
     * member表grade 会员等级 0-注册用户 1-会员 2-会长
     */
    private final String memberGradeZero = "0";
    private final String memberGradeOne = "1";
    private final String memberGradeTwo = "2";

    /**
     * 优惠券表status=   0-未使用 1-已使用 2-已过期
     */
    private String couponStatusNotUsed = "0";
    private String couponStatusAlreadyUsed = "1";
    private String couponStatusExpired = "2";

    /**
     * store表status=0-禁用 1-启用
     */
    private String storeStatusEnable = "1";

    /**
     * orders表status=0-未支付 1-已支付&&未评价 2-已支付&&已评价 3-关闭订单
     */
    private String ordersStatusUnpaid = "0";
    private String ordersStatusPaid = "1";
    private String ordersStatusClosingOrder = "2";

    /**
     * #10=微信jsApi支付 11=微信APP支付 12=微信Native支付 13=微信刷脸支付 14=微信H5支付,20-支付宝扫码,30-银联,40-其他
     */
    @Value("${sys.orders.paymentMethod}")
    private String paymentMethod;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Orders> findAll() {
        return ordersDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Orders> findSearch(Map whereMap, int page, int size) {
        Specification<Orders> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return ordersDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Orders> findSearch(Map whereMap) {
        Specification<Orders> specification = createSpecification(whereMap);
        return ordersDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Orders findById(String id) {
        return ordersDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param orders
     */
    public void addOrders(Orders orders) {
        ordersDao.save(orders);
    }


    /**
     * 增加订单
     *
     * @param ordersRequestModel
     */
    public void add(OrdersRequestModel ordersRequestModel) {
        //这里只给关键信息，足够支付就可以。
        // 然后给队列加ordersId其他信息交给队列进行补全
        LocalDateTime now = LocalDateTime.now();
        Orders orders = new Orders();
        orders.setId(ordersRequestModel.getOrdersId());
        orders.setOpenId(ordersRequestModel.getOpenId());
        orders.setNickname(ordersRequestModel.getNickname());
        orders.setPrice(ordersRequestModel.getPrice());
        orders.setStoreId(ordersRequestModel.getStoreId());
        orders.setPayment(ordersRequestModel.getPayment());
        orders.setPayAmount(ordersRequestModel.getPayAmount());
        orders.setRate(ordersRequestModel.getRate());
        orders.setMemberId(ordersRequestModel.getMemberId());
        orders.setStatus("0");
        String remark = ordersRequestModel.getRemark();
        orders.setRemark(remark);
        orders.setCreatedAt(now);
        orders.setUpdatedAt(now);
        logger.info("orders id=" + orders.getId());
        ordersDao.save(orders);

    }

    public void updateIsPlus(String ordersId) {
        Orders orders = findById(ordersId);
        String remark = orders.getRemark();
        //这里处理买了会员的情况
        String vip1 = "vip1";
        String vip2 = "vip2";
        if (vip1.equals(remark) || (vip2).equals(remark)) {
            //这里新增一个购买了会员的订单
            //更新会员状态
            Member member = JSON.parseObject(memberClient.thirdFindEnableMemberById(orders.getMemberId()), Member.class);
            logger.info("member=" + member.toString());
            member.setIsPlus("vip1".equals(remark) ? "1" : "2");
            //注册码豆+5
            member.setBeans(5);
            member.setTotalBeans(5);
            memberClient.thirdUpdateMemberByMember(JSON.toJSONString(member));
        }
    }


    /**
     * 是否在某个时间区间内
     *
     * @param now
     * @param from
     * @param to
     * @return
     * @throws ParseException
     */
    public boolean belongCalendar(String now, String from, String to) throws ParseException {
        String format = "HH:mm:ss";
        Date nowTime = new SimpleDateFormat(format).parse(now);
        Date startTime = new SimpleDateFormat(format).parse(from);
        Date endTime = new SimpleDateFormat(format).parse(to);

        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 修改
     *
     * @param orders
     */
    public void update(Orders orders) {
        ordersDao.save(orders);
    }

    public void updateByRequestModel(OrdersRequestModel ordersRequestModel) {
        Orders orders = findById(ordersRequestModel.getOrdersId());
        orders.setPayment(ordersRequestModel.getPayment());
        orders.setPrice(ordersRequestModel.getPrice());
        orders.setPayAmount(ordersRequestModel.getPayAmount());
        orders.setRate(ordersRequestModel.getRate());
        orders.setStoreId(ordersRequestModel.getStoreId());
        orders.setStatus("0");
        ordersDao.save(orders);
    }

    /**
     * 根据会员等级和店铺折扣计算该会员在这家店的折扣率
     *
     * @param memberGrade
     * @param storeRate
     * @return
     */
    public Double getMemberRate(String memberGrade, String storeRate) {
        System.out.println("根据会员等级和店铺折扣计算该会员在这家店的折扣率" + memberGrade);
        Double vip1 = Double.parseDouble(JSON.parseObject(storeRate).get("vip1").toString());
        Double vip2 = Double.parseDouble(JSON.parseObject(storeRate).get("vip2").toString());
        if (memberGradeZero.equals(memberGrade)) {
            return 0.0;
        } else if (memberGradeOne.equals(memberGrade)) {
            return vip1;
        } else if (memberGradeTwo.equals(memberGrade)) {
            return vip2;
        } else {
            return 0.0;
        }
    }

    /**
     * 下单时判断支付方式是否可用
     *
     * @param payment 要判断的场景
     * @return true 存在 false 不存在
     */
    public boolean determinePaymemtAvailable(String payment) {
        return paymentMethod.contains(payment);
    }


    /**
     * 下单时判断会员是否可用
     *
     * @param memberInDb
     * @return
     * @throws ParseException
     */
    public Map<String, Object> determineMemberAvailable(Member memberInDb) {
        HashMap<String, Object> map = new HashMap<>(3);
        map.put("flag", false);
        map.put("code", StatusCode.ERROR);
        if (memberInDb == null) {
            map.put("message", "找不到该会员");
            return map;
        }
        if (!memberStatusEnable.equals(memberInDb.getStatus())) {
            map.put("message", "会员状态异常,暂无法购买");
            return map;
        }
        map.put("flag", true);
        map.put("code", StatusCode.SUCCESS);
        map.put("message", "该会员可用");
        return map;
    }

    /**
     * 下单时判断ordersInDb订单是否可用
     *
     * @param ordersInDb
     * @return
     */
    public String determineOrdersAvailable(Orders ordersInDb) {
        logger.info("ordersInDb=" + ordersInDb);
        if (ordersInDb == null) {
            return "找不到该订单";
        }
        if (ordersStatusClosingOrder.equals(ordersInDb.getStatus())) {
            return "订单已关闭";
        }
        if (ordersStatusPaid.equals(ordersInDb.getStatus())) {
            return "订单已支付";
        }
        return "";
    }

//    /**
//     * 下单时判断subOrdersInDb订单是否可用
//     *
//     * @param subOrdersInDb
//     * @return
//     */
//    public String determineSubOrdersAvailable(SubOrders subOrdersInDb) {
//        if (subOrdersInDb == null) {
//            return "找不到该子订单";
//        }
//        if (ordersStatusClosingOrder.equals(subOrdersInDb.getStatus())) {
//            return "子订单已关闭";
//        }
//        if (ordersStatusPaid.equals(subOrdersInDb.getStatus())) {
//            return "子订单已支付";
//        }
//        return "";
//    }

    /**
     * 下单时判断店铺是否可用
     *
     * @param storeInDb
     * @param now
     * @return
     * @throws ParseException
     */
    public String determineStoreAvailable(Store storeInDb, LocalDateTime now) throws ParseException {
        if (storeInDb == null) {
            return "找不到该店铺";
        }
        if (!storeStatusEnable.equals(storeInDb.getStatus())) {
            return "店铺状态异常,暂无法购买";
        }
//        if (storeInDb.getBusinessHoursStart() != null && !"".equals(storeInDb.getBusinessHoursStart())
//                && storeInDb.getBusinessHoursEnd() != null && !"".equals(storeInDb.getBusinessHoursEnd())) {
//            String format = "HH:mm:ss";
//            SimpleDateFormat sdf = new SimpleDateFormat(format);
//            if (!belongCalendar(sdf.format(now), sdf.format(storeInDb.getBusinessHoursStart()), sdf.format(storeInDb.getBusinessHoursEnd()))) {
//                return "店铺已休息,暂无法购买";
//            }
//        } else {
//            return "店铺还没设置营业时间,暂无法购买";
//        }
        return "";
    }

    /**
     * 下单时判断优惠券是否可用
     *
     * @param couponInDb
     * @param storeId
     * @param now
     * @return
     * @throws ParseException
     */
    public String determineCouponAvailable(Coupon couponInDb, String storeId, LocalDateTime now) throws ParseException {
        if (couponInDb == null) {
            return "找不到该优惠券";
        }
        if (!couponInDb.getStoreId().equals(storeId)) {
            return "不是该店发出的优惠券";
        }
        if (couponStatusAlreadyUsed.equals(couponInDb.getStatus())) {
            return "优惠券已被使用";
        }
        if (couponStatusExpired.equals(couponInDb.getStatus())) {
            return "优惠券已过期";
        }

        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        if (sdf.parse(sdf.format(now)).before(sdf.parse(sdf.format(couponInDb.getValidityStart())))) {
            return "还没到优惠券生效时间";
        }
        if (sdf.parse(sdf.format(now)).after(sdf.parse(sdf.format(couponInDb.getValidityEnd())))) {
            return "已过优惠券生效时间";
        }
        return "";
    }

    /**
     * 计算本单使用的充值卡,返回使用的充值卡id
     *
     * @param price
     * @param agentId
     * @param storeId
     * @return
     */
    public ArrayList<String> usePurchases(BigDecimal price, String agentId, String storeId) {
        //存放这单使用的purchase充值卡的ID
        ArrayList<String> purchaseIdList = new ArrayList<>();

        //判断status=1(使用中)的充值卡的余额是否够支付这一单,小票金额-余额的值大于表示不可以支付,小于等于0表示可以支付
        List<Purchase> purchaseList1 = purchaseService.findAllByAgentIdAndStoreIdAndStatusOrderByCreatedAt(agentId, storeId, "1");
        logger.info("使用中的充值卡数量=" + purchaseList1.size());
        for (int i = 0; i < purchaseList1.size(); i++) {
            purchaseIdList.add(purchaseList1.get(i).getId());
            //a.compareTo(b)<1表示a<=b,采购充值卡余额小于等于0的跳过本次循环
            BigDecimal purchaseBalance = purchaseList1.get(i).getBalance();
            if (purchaseBalance.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }
            //价格减去商户余额,大于0表示不足,小于等于0表示充足
            price = price.subtract(purchaseBalance);
            if (price.compareTo(BigDecimal.ZERO) < 1) {
                logger.info("status=1的purchase够用了" + price);
                break;
            } else {
                logger.info("status=1的purchase不够用" + price);
            }
        }
        logger.info("存放使用中的充值卡的ID的数组=" + purchaseIdList.toString());

        if (price.compareTo(BigDecimal.ZERO) < 1) {
            logger.info("status=1的purchase就够用了,不需要使用status=1的purchase");
        } else {
            //判断status=0(未使用)的充值卡的余额是否够支付这一单
            List<Purchase> purchaseList0 = purchaseService.findAllByAgentIdAndStoreIdAndStatusOrderByCreatedAt(agentId, storeId, "0");
            logger.info("商户余额不足,开始使用status=0的purchase,未使用的充值卡有" + purchaseList0.size() + "张,小票金额=" + price);
            if (purchaseList0.size() == 0) {
                logger.info("商户余额不足,因为未使用的充值卡数量为0");
                return purchaseIdList;
            }
            for (int i = 0; i < purchaseList0.size(); i++) {
                //采购充值卡余额小于等于0的跳过
                BigDecimal purchaseBalance = purchaseList0.get(i).getBalance();
                purchaseIdList.add(purchaseList0.get(i).getId());
                logger.info("第" + purchaseList0.get(i).getId() + "张充值卡余额=" + purchaseBalance + ";" + price);
                if (purchaseBalance.compareTo(BigDecimal.ZERO) < 1) {
                    continue;
                }
                //价格减去商户余额,大于0表示不足,小于等于0表示充足
                price = price.subtract(purchaseBalance);
                logger.info("第" + purchaseList0.get(i).getId() + "张充值卡余额=" + purchaseBalance + ";" + price);
                //使用中的充值卡0张,判断未使用的充值卡
                if (price.compareTo(BigDecimal.ZERO) < 1) {
                    //price<=0,表示此时余额充足
                    logger.info("2第" + purchaseList0.get(i).getId() + "张充值卡余额=" + purchaseBalance + ";" + price);
                    break;
                } else {
                    //最后一张未使用的充值卡且price>0
                    if (i == purchaseList0.size() - 1 && price.compareTo(BigDecimal.ZERO) == 1) {
                        logger.info("商户余额不足,因为未使用的充值卡不够用" + price);
                    }
                }
            }
        }
        logger.info("存放未使用的purchase卡的ID的数组=" + purchaseIdList.toString());
        return purchaseIdList;
    }

    /**
     * 计算本单的城市合伙人本金=小票金额*商家折扣,并修改商家余额
     *
     * @param price
     * @param purchaseIdList
     * @return
     */
    public BigDecimal getPrincipal(LocalDateTime now, BigDecimal price, ArrayList<String> purchaseIdList) {
        //计算余额
        BigDecimal priceToBalance = price;
        //城市合伙人本金=小票金额*商家折扣
        BigDecimal priceToPrincipal = BigDecimal.ZERO;
        BigDecimal principal = BigDecimal.ZERO;
        //除最后一张额度卡,本金=前面几张余额*rate的和
        for (int i = 0; i < purchaseIdList.size(); i++) {
            Purchase purchaseInDb = purchaseService.findById(purchaseIdList.get(i));
            //只用一张充值卡,本金=余额*rate
            if (purchaseIdList.size() == 1) {
                //本金=余额*rate
                principal = price.multiply(BigDecimal.valueOf(purchaseInDb.getRate()));
                //a.compareTo(b)==1表示a>b,充值卡余额-小票金额>0表示充值卡仍有余额,
                BigDecimal balance = purchaseInDb.getBalance().subtract(price);
                if (balance.compareTo(BigDecimal.ZERO) == 1) {
                    purchaseInDb.setBalance(balance);
                    purchaseInDb.setStatus("1");
                } else {
                    purchaseInDb.setBalance(BigDecimal.ZERO);
                    purchaseInDb.setStatus("2");
                }
                purchaseInDb.setUpdatedAt(now);
                purchaseService.update(purchaseInDb);
                break;
            }
            //不止用一张充值卡,本金=前面几张余额*rate的和
            if (i == purchaseIdList.size() - 1) {
                //最后一张充值卡的本金=price余额*rate
                BigDecimal multiply = price.multiply(BigDecimal.valueOf(purchaseInDb.getRate()));
                principal = principal.add(multiply);

                BigDecimal balance = purchaseInDb.getBalance().subtract(price);
                purchaseInDb.setBalance(balance);
                if (balance.compareTo(BigDecimal.ZERO) == 1) {
                    purchaseInDb.setStatus("1");
                } else {
                    purchaseInDb.setStatus("2");
                }
                purchaseInDb.setUpdatedAt(now);
                purchaseService.update(purchaseInDb);
            } else {
                //这张充值卡的本金
                BigDecimal multiply = purchaseInDb.getBalance().multiply(BigDecimal.valueOf(purchaseInDb.getRate()));
                //总本金=前面几张余额*rate的和
                principal = principal.add(multiply);
                //小票金额-充值卡余额
                price = price.subtract(purchaseInDb.getBalance());

                purchaseInDb.setBalance(BigDecimal.ZERO);
                purchaseInDb.setStatus("2");
                purchaseInDb.setUpdatedAt(now);
            }
        }
        return principal;
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        ordersDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Orders> createSpecification(Map searchMap) {
        return new Specification<Orders>() {
            @Override
            public Predicate toPredicate(Root<Orders> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 订单id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 外部交易号
                String transactionNo = "transactionNo";
                if (searchMap.get(transactionNo) != null && !"".equals(searchMap.get(transactionNo))) {
                    predicateList.add(cb.like(root.get(transactionNo).as(String.class), "%" + (String) searchMap.get(transactionNo) + "%"));
                }
                // 支付方式 10-微信扫码,20-支付宝扫码,30-银联,40-其他
                String payment = "payment";
                if (searchMap.get(payment) != null && !"".equals(searchMap.get(payment))) {
                    predicateList.add(cb.like(root.get(payment).as(String.class), "%" + (String) searchMap.get(payment) + "%"));
                }
                // 会员id
                String memberId = "memberId";
                if (searchMap.get(memberId) != null && !"".equals(searchMap.get(memberId))) {
                    predicateList.add(cb.like(root.get(memberId).as(String.class), "%" + searchMap.get(memberId) + "%"));
                }
                // 会员昵称
                String nickname = "nickname";
                if (searchMap.get(nickname) != null && !"".equals(searchMap.get(nickname))) {
                    predicateList.add(cb.like(root.get(nickname).as(String.class), "%" + (String) searchMap.get(nickname) + "%"));
                }
                // 会员等级
                String memberGrade = "memberGrade";
                if (searchMap.get(memberGrade) != null && !"".equals(searchMap.get(memberGrade))) {
                    predicateList.add(cb.like(root.get(memberGrade).as(String.class), "%" + (String) searchMap.get(memberGrade) + "%"));
                }
                // 商家id
                String companyId = "companyId";
                if (searchMap.get(companyId) != null && !"".equals(searchMap.get(companyId))) {
                    predicateList.add(cb.like(root.get(companyId).as(String.class), "%" + (String) searchMap.get(companyId) + "%"));
                }
                // 店铺名字
                String storeName = "storeName";
                if (searchMap.get(storeName) != null && !"".equals(searchMap.get(storeName))) {
                    predicateList.add(cb.like(root.get(storeName).as(String.class), "%" + (String) searchMap.get(storeName) + "%"));
                }
                // 店铺id
                String storeId = "storeId";
                if (searchMap.get(storeId) != null && !"".equals(searchMap.get(storeId))) {
                    predicateList.add(cb.like(root.get(storeId).as(String.class), "%" + (String) searchMap.get(storeId) + "%"));
                }
                // 代理商id
                String agentId = "agentId";
                if (searchMap.get(agentId) != null && !"".equals(searchMap.get(agentId))) {
                    predicateList.add(cb.like(root.get(agentId).as(String.class), "%" + (String) searchMap.get(agentId) + "%"));
                }
                // 状态 0-未支付 1-已支付 2-关闭订单
                String status = "status";
                if (searchMap.get(status) != null && !"".equals(searchMap.get(status))) {
                    predicateList.add(cb.like(root.get(status).as(String.class), "%" + (String) searchMap.get(status) + "%"));
                }

                // 是否使用了优惠券 0-未使用 1-已使用
                String hasCoupon = "hasCoupon";
                if (searchMap.get(hasCoupon) != null && !"".equals(searchMap.get(hasCoupon))) {
                    predicateList.add(cb.like(root.get(hasCoupon).as(String.class), "%" + (String) searchMap.get(hasCoupon) + "%"));
                }
                // 优惠券id
                String couponId = "couponId";
                if (searchMap.get(couponId) != null && !"".equals(searchMap.get(couponId))) {
                    predicateList.add(cb.like(root.get(couponId).as(String.class), "%" + (String) searchMap.get(couponId) + "%"));
                }
                // 地址id
                String addressId = "addressId";
                if (searchMap.get(addressId) != null && !"".equals(searchMap.get(addressId))) {
                    predicateList.add(cb.like(root.get(addressId).as(String.class), "%" + (String) searchMap.get(addressId) + "%"));
                }
                //备注,是否plus会员 0-游客/注册用户,1-付了一块钱->会员,2-付了198->plus会员
                String remark = "remark";
                if (searchMap.get(remark) != null && !"".equals(searchMap.get(remark))) {
                    predicateList.add(cb.like(root.get(remark).as(String.class), "%" + (String) searchMap.get(remark) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(Date.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * orders根据memberId查找总订单
     *
     * @param memberId
     * @param page
     * @param size
     * @return
     */
    public Page<Orders> findOrdersByMemberIdAndTotal(String memberId, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return ordersDao.findOrdersByMemberIdAndTotal(memberId, pageable);
    }

    /**
     * 根据memberID查找会员名下所有未删除的订单并分页
     *
     * @param memberId
     * @param page
     * @param size
     * @return
     */
    public Page<Orders> findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(String memberId, int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return ordersDao.findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(memberId, pageable);
    }


    /**
     * 通过id和memberId查询某一订单
     *
     * @param id
     * @param memberId
     * @return
     */
    public Orders findByIdAndMemberId(String id, String memberId) {
        return ordersDao.findByIdAndMemberId(id, memberId);
    }

    /**
     * 后台订单列表并分页
     *
     * @param page
     * @param size
     * @return
     */
    public Page<Orders> findAll(int page, int size) {
        Pageable pageable = PageRequest.of(page - 1, size);
        return ordersDao.findAll(pageable);
    }

    public HashMap<String, Integer> countAllStatusOrders(String memberId) {
        Integer[] count = ordersDao.countAllStatusOrders(memberId).get(0);
        HashMap<String, Integer> countMap = new HashMap<>(4);
        countMap.put("total", count[0]);
        countMap.put("not_pay", count[1]);
        countMap.put("paid", count[2]);
        countMap.put("closed", count[3]);
        return countMap;
    }


}
